import store from '../index.js';
import http from '@/common/http.js'
import tim from '@/common/tim.js'
import $api from 'api'

const state = {
	userInfo: uni.getStorageSync('userInfo') || '',
	userCenter: uni.getStorageSync('userCenter') || '',
	locationCity:''
}

const mutations = {
	// 更新用户信息
	UPDATE_USERINFO: function(state, payLoad) {
		state.userInfo = payLoad
		uni.setStorageSync('userInfo', payLoad);
	},
	// 更新个人主页用户信息
	UPDATE_USERCENTER_USERINFO: function(state, payLoad) {
		state.userCenter = payLoad
		uni.setStorageSync('userCenter', payLoad);
	},
	// 设置当前所在城市
	LOCATION_CITY: function(state, payLoad) {
		state.locationCity = payLoad
	},
}

const actions = {
	// 获取用户信息
	async refreshUserInfo(context) {
		console.log(context)
		let userInfo = await $api.getUserInfo()
		context.commit('UPDATE_USERINFO', userInfo.data)
	},

	async getUserInfo(context) {
		console.log(context)
		let userInfo = await $api.getUserInfo()
		
		let loginInfo = null
		loginInfo = tim.tim.login({
			userID:userInfo.data.im_account,
			userSig:userInfo.data.user_sig,
		})
		console.log(userInfo.data.im_account)
		console.log(userInfo.data.user_sig)
		loginInfo.then(res=>{
			console.log('----------iM登录信息----------')
			console.log(res)
			// 获取全量的会话列表
			let promise = tim.tim.getConversationList();
			promise.then((imResponse) => {
				console.log(imResponse)
				this.messageNum = 0
				this.conversationList = imResponse.data.conversationList; // 全量的会话列表，用该列表覆盖原有的会话列表
				console.log("this.conversationList: ", this.conversationList);
				this.conversationList.forEach(item => {
					if(item.conversationID!="@TIM#SYSTEM"){
						this.messageNum += item.unreadCount
					}
				})
				tabbar[3].count = this.messageNum
			}).catch(function(imError) {
				console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
			});
		})
		
		
		context.commit('UPDATE_USERINFO', userInfo.data)
	},
	// 获取个人主页用户信息
	async getUserCenter(context,user_id) {
		let userInfo = await $api.getUserCenter({
			user_id
		})
		context.commit('UPDATE_USERCENTER_USERINFO', userInfo.data)
	}
}

export default {
	state,
	mutations,
	actions
}
